package com.dkha.server.schedule;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dkha.common.enums.YNEnums;
import com.dkha.server.modules.entities.FaceCameraEntity;
import com.dkha.server.services.FaceCameraService;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FrameGrabber;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: CheckCameraTimer
 * @Description:
 * @author: yanping
 * @date: 2020-01-07 10:25:50
 * @Copyright: 成都电科惠安
 */

@Slf4j
@Component
public class CheckCameraTimer {

    @Autowired
    private FaceCameraService faceCameraService;

    /**
     * 检测摄像头是否可用，项目启动10秒后执行，间隔时间为两小时
     */
    @Scheduled(fixedDelay = 1000 * 3600 * 2, initialDelay = 10000)
    public void checkCameras() {
        List<FaceCameraEntity> cameras = faceCameraService.list(new QueryWrapper<FaceCameraEntity>().eq("is_valid", YNEnums.YES.code));
        List<FaceCameraEntity> updates = new ArrayList<>();
        for (FaceCameraEntity faceCameraEntity : cameras) {
            String rtspUrl = faceCameraEntity.getRtspUrl();
            FFmpegFrameGrabber fFmpegFrameGrabber = null;
            try {
                fFmpegFrameGrabber = new FFmpegFrameGrabber(rtspUrl);
                fFmpegFrameGrabber.start();
                fFmpegFrameGrabber.stop();
                faceCameraEntity.setStatus(YNEnums.YES.code);
                updates.add(faceCameraEntity);
            } catch (FrameGrabber.Exception e) {
                log.error(e.getMessage());
                faceCameraEntity.setStatus(YNEnums.NO.code);
                updates.add(faceCameraEntity);
                continue;
            } finally {

            }

        }
        if(updates.size() > 0){
            faceCameraService.updateBatchById(updates);
        }

    }


}
